<?php


class ImageResizer extends ContentController 
{
	
	var $extensions = array ( 'jpg', 'gif', 'png' );

	function _acceptedCommand ()
	{
		$command = $this->_normalizedCommand();
		$dimensions = $this->_getDimensions();
		if ( !is_array( $dimensions ))
		{
			$this->log( 'not under my competences' );
			return false;
		}
		return true;
	}
	function _getDimensions()
	{
		$command = $this->_normalizedCommand();
		$dimensions = explode ( 'x', $command );
		$dimensions = array_pad ( $dimensions, 2, null );
		
		//assigning x e y only for clearness
		$x = $dimensions[0];
		$y = $dimensions[1];
		
		if ( 
			(!$x && !$y ) 
			|| ( !is_numeric( $x ) && !is_null ( $x ))
			|| ( !is_numeric( $y )  && !is_null ( $y ) ) 
		)
		{
			$this->log ( 'null/wrong dimensions. aborting.')	;
			return false;
		}
		
		return $dimensions;
	}
	function _normalizedCommand ()
	{
		return $this->predefinedFormatConvert ( $this->_getCommand() );
	}
	function generateFile ()
	{
		
		$dimensions = $this->_getDimensions();
		if ( !is_array( $dimensions )) return false;
		//assigning x e y only for clearness
		$x = $dimensions[0];
		$y = $dimensions[1];
		
		$this->log ( 'generateFile params: ',  get_defined_vars() );
		
		if ( !$this->Controller->configuration[ 'stopGeneration' ] )
		{
			$generated = $this->renderContent( $this->sourceFile, $this->destinationFile, $x, $y );
			$this->log ( 'generated:'.$generated );
			return $generated;
		} else {
			$this->log ( 'stopGeneration activated. Generation Stopped.');
			return false;
		}
	}
	function predefinedFormatConvert ( $format )
	{
		
		if ( isset( $this->formats[ $format ] ) )
		{
			$newFormat = $this->formats[ $format ];
			$oldFormat = $format;
			$format = $newFormat[ 'w' ].'x'.$newFormat[ 'h' ];
			$this->log( 'predefined formats compatibility: '.$oldFormat.' becomes '.$format );
			
		} else {
			$this->log ( 'no predefined format conversion required' );
		}
		return $format;
	}
	
	function _processRequest()
	{
		$dimensions = $this->_getDimensions();
		if ( !is_array( $dimensions )) return false;
		//assigning x e y only for clearness
		$x = $dimensions[0];
		$y = $dimensions[1];
		
		$this->log ( 'generateFile params: ',  $dimensions );
		
		if ( !$this->Controller->configuration[ 'stopGeneration' ] )
		{
			$generated = $this->renderContent( $this->sourceFilename() , $this->destinationFilename(), $x, $y );
			$this->log ( 'generated:'.$generated );
			return $generated;
		} else {
			$this->log ( 'stopGeneration activated. Generation Stopped.');
			return false;
		}
		
	}
}

?>